package com.calciominoBeta.Activity;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.calciomio.app.R;
import com.calciominoBeta.Activity.db.DbSupport;
import com.calciominoBeta.Activity.db.TableDb;
import com.calciominoBeta.Activity.task.Task;
import com.calciominoBeta.Activity.task.TaskType;
import com.calciominoBeta.Adapter.Accueil_Adapter;
import com.calciominoBeta.Entity.InfoOj;
import com.calciominoBeta.Util.Sdata;
import com.calciominoBeta.Util.Util;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.telpoo.frame.model.BaseModel;
import com.telpoo.frame.object.BaseObject;
import com.telpoo.frame.utils.Mlog;

public class AQFragmentVideo extends BaseDetailfm implements
		MyFragmentInterface {
	private TextView tv_title, tv_date_text, tv_author, tv_type, tv_content,
			url_video, html;
	private WebView webViewVideo;
	private WebView webtitle;
	private Accueil_Adapter adapter;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	protected DisplayImageOptions options;
	private ImageView img_share_post;
	ArrayList<InfoOj> dataLv = null;
	ListView lv_accueil;
	protected int itemHeight;

	private InfoOj oj;
	private Context context;
	public String youtube_id;
	String myHtmlString;
	ProgressBar pro;
	String urlshare = null;
	String temType = "";
	String pish = "https://www.youtube.com/watch?v=";
	NetworkInfo activeNetwork;
	ConnectivityManager conMgr;
	Handler mHandler = new Handler();

	public AQFragmentVideo() {
	}

	public static AQFragmentVideo getInstance(InfoOj oj, Context context) {
		AQFragmentVideo aq = new AQFragmentVideo();
		aq.setOj(oj, context);
		return aq;
	}

	private void setOj(InfoOj oj, Context context) {
		this.youtube_id = oj.get(InfoOj.VIDEO_URL);
		this.oj = oj;
		this.context = context;
		this.temType = oj.get(InfoOj.TYPE);
	}

	View v;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = inflater.inflate(R.layout.fm_detail_video, container, false);
		tv_title = (TextView) v.findViewById(R.id.tv_title1);
		tv_date_text = (TextView) v.findViewById(R.id.tv_date_text1);
		tv_type = (TextView) v.findViewById(R.id.tv_type1);
		webViewVideo = (WebView) v.findViewById(R.id.webvideo);
		webtitle = (WebView) v.findViewById(R.id.webtitile);
		lv_accueil = (ListView) v.findViewById(R.id.detail_list);
		img_share_post = (ImageView) v.findViewById(R.id.img_share_post);
		ImageView[] img = { img_share_post, };
		Util.hilightBtn(img);
		pro = (ProgressBar) v.findViewById(R.id.pro);
		conMgr = (ConnectivityManager) getActivity().getSystemService(
				Context.CONNECTIVITY_SERVICE);
		activeNetwork = conMgr.getActiveNetworkInfo();
		if (Util.checkinternet1(getActivity()) == false) {
			pro.setVisibility(View.GONE);
		}
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		img_share_post.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				share(urlshare);
			}
		});

		String id = oj.get(InfoOj.ID);
		getData(id);
		adapter = new Accueil_Adapter(getActivity(), imageLoader, options);
		lv_accueil.setAdapter(adapter);

		loadDataObjHome();
		lv_accueil.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				Accueil_Adapter madapter = (Accueil_Adapter) arg0.getAdapter();

				ArrayList<InfoOj> arrNews = madapter.getFull();
				Sdata.dataLv = arrNews;
				Sdata.position = position;
				startActivity(new Intent(getActivity(), AQDetailActivity.class));

			}
		});

	}

	void loadDataObjHome() {

		ArrayList<InfoOj> dataHome = DbSupport.getCache(TableDb.HOME);

		ArrayList<InfoOj> dataHome1 = new ArrayList<InfoOj>();
		int count = (dataHome.size() > 5 ? 5 : dataHome.size());
		for (int i = 0; i < count; i++) {
			dataHome1.add(dataHome.get(i));
		}
		adapter.setData(dataHome1);
		setListViewHeightBasedOnChildren(lv_accueil);
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < 5; i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}

	private void getData(String id) {

		ArrayList<String> list = new ArrayList<String>();
		list.add(id);

		BaseModel model = new BaseModel() {
			@SuppressWarnings("deprecation")
			@Override
			public void onSuccess(int taskType, ArrayList<?> list, String msg) {
				super.onSuccess(taskType, list, msg);
				if (taskType == TaskType.DETAIL) {
					BaseObject ojj = (BaseObject) list.get(0);
					InfoOj infoDetail = new InfoOj();
					infoDetail.setParams(ojj.getParams());
					String youid = infoDetail.get(InfoOj.VIDEO_URL);
					if (youid != null)
						youtube_id = youid;
					Mlog.T("youtube_id=" + youtube_id);

					try {
						urlshare = infoDetail.get(InfoOj.URL);
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						tv_title.setText(Html.fromHtml(infoDetail.get(
								InfoOj.TITLE).toUpperCase()));

					} catch (Exception e) {
						return;
					}

					if (infoDetail.get(InfoOj.TYPE).equalsIgnoreCase("breves")) {
						tv_type.setText(R.string.breves);
						tv_type.setTextColor(context.getResources()
								.getColorStateList(R.color.breves));
					}
					if (infoDetail.get(InfoOj.TYPE).equalsIgnoreCase("videos")) {
						tv_type.setText(getString(R.string.video_fr));
						tv_type.setTextColor(context.getResources()
								.getColorStateList(R.color.video));
					}
					if (infoDetail.get(InfoOj.TYPE)
							.equalsIgnoreCase("articles")) {
						tv_type.setText("ARTICLES");
						tv_type.setTextColor(context.getResources()
								.getColorStateList(R.color.articles));
					}

					// title new posh

					tv_title.setTextColor(context.getResources()
							.getColorStateList(R.color.detail_title));
					tv_date_text.setText(infoDetail.get(InfoOj.DATE_TEXT));
					String mhtml = "<html><head><style type=\"text/css\">@font-face {font-family: 'arial';src: url(\"file:///android_asset/font/fontawesome-webfont.ttf\")}body {font-family: 'arial';font-size: medium;text-align: justify;}line-height:20px;</style></head><body>";
					String nhtml = "</body></html>";
					String mcontent = mhtml + infoDetail.get(InfoOj.CONTENT)
							+ nhtml;
					webtitle.getSettings().setJavaScriptEnabled(true);
					webtitle.getSettings().setPluginState(
							WebSettings.PluginState.ON);
					webtitle.loadDataWithBaseURL("", mcontent, "text/html",
							"utf-8", "");
					webtitle.setWebViewClient(new WebViewClient() {
						@Override
						public void onPageFinished(WebView view, String url) {

							pro.setVisibility(View.GONE);
						};

						@Override
						public void onReceivedError(WebView view,
								int errorCode, String description,
								String failingUrl) {
							pro.setVisibility(View.GONE);
						};
					});

					// webvideo new posh

					myHtmlString = pish + youtube_id;
					webViewVideo.setWebViewClient(new WebViewClient() {
						@Override
						public void onPageFinished(WebView view, String url) {
							pro.setVisibility(View.GONE);
						};

						@Override
						public void onReceivedError(WebView view,
								int errorCode, String description,
								String failingUrl) {
							pro.setVisibility(View.GONE);
						};
					});

					webViewVideo.getSettings().setJavaScriptEnabled(true);
					webViewVideo.getSettings().setPluginState(
							WebSettings.PluginState.ON);
					if (youtube_id != null && youtube_id.length() > 0) {
						webViewVideo.loadUrl(myHtmlString);
						webViewVideo.setVisibility(View.VISIBLE);
					} else {
						webViewVideo.setVisibility(View.GONE);
					}

					lv_accueil
							.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> arg0,
										View arg1, int position, long arg3) {

									Accueil_Adapter madapter = (Accueil_Adapter) arg0
											.getAdapter();

									ArrayList<InfoOj> arrNews = madapter
											.getFull();
									Sdata.dataLv = arrNews;
									webViewVideo.loadUrl(myHtmlString);
									Sdata.position = position;
									startActivity(new Intent(getActivity(),
											AQDetailActivity.class));

								}
							});

				}

			}

			@Override
			public void onFail(int taskType, String msg) {
				// TODO Auto-generated method stub
				super.onFail(taskType, msg);
			}
		};
		new Task(model, TaskType.DETAIL, list, getActivity()).exe();

	}

	@Override
	public void onVisible(int position) {
		// TODO Auto-generated method stub
		try {
			if (temType.equals("videos"))
				webViewVideo.setVisibility(View.VISIBLE);

		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	public void onInVisible(int position) {
		try {
			webViewVideo.loadUrl(myHtmlString);
		} catch (Exception e) {
		}

	}

	@Override
	public void share(String link) {
		super.share(urlshare);
	}

}
